package com.zxl.template.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.VpnService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.sslvpn_android_client.VPNServiceManager;
import com.zxl.template.App;
import com.zxl.template.R;
import com.zxl.template.base.BaseAty;
import com.zxl.template.constant.constant;
import com.zxl.template.model.DocParams;
import com.zxl.template.model.MsgEvent;
import com.zxl.template.model.Vpn;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LCacheTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LLoginControl;
import com.zxl.zlibrary.tool.LStatusBarTool;
import com.zxl.zlibrary.tool.LToast;
import com.zxl.zlibrary.tool.LogTool;
import com.zxl.zlibrary.view.LClearEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;
import okhttp3.Call;

public class LoginActivity extends BaseAty implements constant {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.et_mobile)
    LClearEditText etMobile;
    @BindView(R.id.et_password)
    LClearEditText etPassword;
    @BindView(R.id.et_http)
    LClearEditText etHttp;
    @BindView(R.id.checkBox)
    AppCompatCheckBox checkBox;
    @BindView(R.id.switch_view)
    SwitchView switchView;

    private boolean vpnFlag = false;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            JSONObject json = JSON.parseObject((String) msg.obj);
            int type = json.getInteger("type");
            int result = json.getInteger("result");
            String reason = json.getString("reason");

            //登录成功
            if (result == 2001) {
                vpnFlag = true;
                LogTool.e(TAG + "vpn2001：" + result + "，" + reason);
            } else if (result == 10000) {
                LogTool.e(TAG + "vpn10000：" + result + "，" + reason);
                int nextAuthentication = json.getInteger("nextAuthentication");
                if (nextAuthentication == VPNServiceManager.AUTHENTICATION_FINISH) {
                    App.mApp.mVpn.startVPNService(LoginActivity.this);
                }
            } else {
                //错误情况
                LogTool.e(TAG + "vpn报错了：" + result);
                LToast.normal("vpn账号或者密码错误，请重新设置。");
                clearVpn();
                LActivityTool.startActivity(VpnAty.class);
            }
        }
    };
    private boolean checked;
    private String vpnStr;
    private Vpn vpnJson;
    private LCacheTool vpnConfigCache;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        LStatusBarTool.immersive(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        initView();
        initVpn();
    }

    private void initVpn() {
        App.mApp.mVpn.addBroadcastReceiver(BROADCAST_VPN_SERVICE);
        App.mApp.mVpn.addHandler(handler);
        if (App.mApp.mVpn.isOnline()) {
            vpnFlag = true;
        }

        LCacheTool vpnFlagCache = LCacheTool.getInstance("vpn_flag");
        if (LEmptyTool.isNotEmpty(vpnFlagCache)) {
            String vpn = vpnFlagCache.getString("vpn");
            if (vpn != null)
                if (vpn.equals("1")) {
                    if (!App.mApp.mVpn.isOnline())
                        vpnControl(true);
                    switchView.toggleSwitch(true);
                } else {
                    vpnControl(false);
                    switchView.toggleSwitch(false);
                }
        } else {
            switchView.toggleSwitch(false);
        }

        switchView.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                vpnStr = vpnConfigCache.getString("vpn_config");
                if (LEmptyTool.isNotEmpty(vpnStr)) {
                    view.toggleSwitch(true);
                    vpnFlagCache.put("vpn", "1");
                    if (!App.mApp.mVpn.isOnline()) {
                        vpnControl(true);
                    }
                } else {
                    view.toggleSwitch(false);
                    LToast.normal("请先设置VPN");
                    LActivityTool.startActivity(VpnAty.class);
                }
            }

            @Override
            public void toggleToOff(SwitchView view) {
                view.toggleSwitch(false);
                vpnFlagCache.put("vpn", "0");
                vpnControl(false);
            }
        });
    }

    /**
     * VPN 控制
     *
     * @param flag
     */
    public void vpnControl(boolean flag) {
        if (flag) {
            //准备启动服务
            Intent intent = VpnService.prepare(LoginActivity.this);
            if (intent != null) {
                startActivityForResult(intent, 0);
            } else {
                onActivityResult(0, RESULT_OK, null);
            }
        } else {
            App.mApp.mVpn.stopService(LoginActivity.this);
        }
    }

    private void clearVpn() {
        LCacheTool vpnConfig = LCacheTool.getInstance("vpn_config");
        vpnConfig.put("vpn_config", "");

        LCacheTool cacheTool = LCacheTool.getInstance("vpn_flag");
        cacheTool.put("vpn", "0");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {
            vpnStr = vpnConfigCache.getString("vpn_config");

            if (LEmptyTool.isNotEmpty(vpnStr)) {
                vpnJson = JSON.parseObject(vpnStr, Vpn.class);
            }
            if (LEmptyTool.isNotEmpty(vpnJson)) {
                if (!App.mApp.mVpn.isOnline())
                    App.mApp.mVpn.authWithAccount(LoginActivity.this, vpnJson.vpnIp, Integer.parseInt(vpnJson.vpnPort), vpnJson.vpnName, vpnJson.vpnPsd);
            }
        }

    }

    private void initView() {
//        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.colorPrimary).line(1, R.color.white).radius(16).into(etMobile);
//        DevShapeUtils.shape(DevShape.RECTANGLE).solid(R.color.colorPrimary).line(1, R.color.white).radius(16).into(etPassword);

        LCacheTool cacheTool = LCacheTool.getInstance("http");
        String api = cacheTool.getString("api");
        if (LEmptyTool.isNotEmpty(api)) {
            etHttp.setText(api);
        }


        vpnConfigCache = LCacheTool.getInstance("vpn_config");
        vpnStr = vpnConfigCache.getString("vpn_config");
        if (LEmptyTool.isNotEmpty(vpnStr)) {
            vpnJson = JSON.parseObject(vpnStr, Vpn.class);
        }

        checkBox.setChecked(true);
        checked = checkBox.isChecked();
        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            checked = isChecked;
        });

        String loginName = LLoginControl.readLoginName(this);
        if (LEmptyTool.isNotEmpty(loginName)) {
            etMobile.setText(loginName);
            String pass = LLoginControl.readPasswordForName(this, loginName);
            etPassword.setText(pass);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgEvent<DocParams> event) {
        if (event.type.equals("vpn_login")) {
            if (!App.mApp.mVpn.isOnline()) {
                vpnStr = vpnConfigCache.getString("vpn_config");
                if (LEmptyTool.isNotEmpty(vpnStr)) {
                    vpnJson = JSON.parseObject(vpnStr, Vpn.class);
                }
                vpnControl(true);
                checkBox.setChecked(true);
            }
        }
    }

    @OnClick({R.id.btn_save, R.id.tv_set_address, R.id.tv_vpn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                String mobile = Objects.requireNonNull(etMobile.getText()).toString();
                String password = Objects.requireNonNull(etPassword.getText()).toString();
                String http = Objects.requireNonNull(etHttp.getText()).toString();


                if (LEmptyTool.isEmpty(http)) {
                    etHttp.setShakeAnimation();
                    LToast.normal("请输入地址");
                    return;
                }

                if (TextUtils.isEmpty(mobile)) {
                    etMobile.setShakeAnimation();
                    LToast.normal("请输入账号");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    etPassword.setShakeAnimation();
                    LToast.normal("请输入密码");
                    return;
                }

                if (LEmptyTool.isEmpty(vpnStr)) {
                    LToast.normal("请设置vpn");
                    return;
                }

                if (switchView.isOpened()) {
                    if (!vpnFlag) {
                        LToast.normal("vpn正在启动，稍后再试");
                        return;
                    }
                } else {
                    LToast.normal("请打开vpn.");
                    return;
                }

                //设置地址
                LCacheTool cacheTool = LCacheTool.getInstance("http");
                cacheTool.put("api", http);

                mApi.initApi(http);


                ProgressDialog progressDialog = ProgressDialog.show(this, "", "正在登录...", true);

                mApi.login(this, mobile, password, mApi.new LoginCallback() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogTool.e(TAG, e);
                        LToast.error(e.getLocalizedMessage());
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Object o, int i) {
                        progressDialog.dismiss();
                        LToast.success("登录成功.");
                        mApi.username = mobile;
                        mApi.password = password;

                        if (checked) {
                            LLoginControl.saveLoginName(LoginActivity.this, mobile);
                            LLoginControl.savePasswordForName(LoginActivity.this, mobile, password);
                        }

                        LActivityTool.startActivity(MainActivity.class);
                        finish();
                    }
                });

                break;

            case R.id.tv_set_address:

                break;
            //vpn设置
            case R.id.tv_vpn:
                LActivityTool.startActivity(VpnAty.class);
                break;

            default:

                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        if (LEmptyTool.isNotEmpty(App.mApp.mVpn)) {
            App.mApp.mVpn.removeHandler(handler);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (LEmptyTool.isNotEmpty(App.mApp.mVpn)) {
            App.mApp.mVpn.removeHandler(handler);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (LEmptyTool.isNotEmpty(App.mApp.mVpn)) {
            App.mApp.mVpn.removeHandler(handler);
        }
    }
}
